package site.xuqing.autohelperengine.local.overlay;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Point;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.lang.ref.WeakReference;
import java.util.Timer;
import java.util.TimerTask;

import androidx.annotation.Nullable;
import site.xuqing.autohelperengine.R;
import site.xuqing.autohelperengine.Step;
import site.xuqing.autohelperengine.StepManager;
import site.xuqing.autohelperengine.local.bean.StepLocalBean;
import site.xuqing.autohelperengine.local.bean.StepLocalType;
import site.xuqing.autohelperengine.util.LogUtil;
import site.xuqing.autohelperengine.util.StepExecutorImpl;

/**
 * @author xuqing
 */
public class CoverView extends LinearLayout implements View.OnTouchListener {
    private GestureDetector mGestureDetector;
    private MyHandler myHandler;
    private long startTime = 0;
    private StepExecutorImpl stepUtil=new StepExecutorImpl();
    private Timer timer;
    private static int executeTime = 0;

    private TextView timeInfo;
    private LinearLayout viewCover;

    public CoverView(Context context) {
        this(context, null);
    }

    public CoverView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        LayoutInflater.from(context).inflate(R.layout.float_cover, this);
        mGestureDetector = new GestureDetector(context, new MyOnGestureListener());
        initView();
    }

    @SuppressLint("ClickableViewAccessibility")
    private void initView() {
        timeInfo=findViewById(R.id.timeInfo);
        viewCover=findViewById(R.id.view_cover);
        viewCover.setOnTouchListener(this);
        myHandler = new MyHandler(timeInfo);
        timer=new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                System.out.println("------------"+this.hashCode());
                myHandler.sendEmptyMessage(0);
            }
        }, 0, 10);
        initData();
    }

    public void initData(){
        System.out.println("计时开始");
        startTime = System.currentTimeMillis();
        executeTime=0;
    }

    static class MyHandler extends Handler {
        private WeakReference<TextView> myTextViewReference;

        MyHandler(TextView timeInfo) {
            myTextViewReference = new WeakReference<>(timeInfo);
        }

        @Override
        public void handleMessage(Message msg) {
            final TextView timeInfo = myTextViewReference.get();
            if (timeInfo != null) {
                executeTime++;
                String timeInfoStr = formatTimeToStr(executeTime);
                timeInfo.setText(timeInfoStr);
            }
        }
    }

    private static String formatTimeToStr(int time) {
        String msStr = "00";
        String sStr = "00";
        String mStr = "00";
        int msInt = 0;
        int sInt = 0;
        int mInt = 0;
        if (time < 100) {
            msInt = time;
        } else if (time > 100 && time < 6000) {
            msInt=time%100;
            sInt = time / 100;
        } else if (time > 6000 && time < 600000) {
            msInt=time%100;
            sInt=time/100%60;
            mInt=time/100/60;
        } else {
            msInt=99;
            sInt=59;
            mInt=99;
            msStr = "99";
            sStr = "59";
            mStr = "99";
        }

        if (msInt < 10) {
            msStr = "0" + msInt;
        } else {
            msStr = msInt + "";
        }
        if (sInt<10){
            sStr="0"+sInt;
        }else{
            sStr=sInt+"";
        }
        if (mInt<10){
            mStr="0"+mInt;
        }else{
            mStr=mInt+"";
        }
        return "当前步骤操作时间：\n"+mStr + "分" + sStr + "秒" + "  " + msStr;
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        mGestureDetector.onTouchEvent(event);
        return true;
    }

    private String getActionName(int action) {
        String name = "";
        switch (action) {
            case MotionEvent.ACTION_DOWN: {
                name = "ACTION_DOWN";
                break;
            }
            case MotionEvent.ACTION_MOVE: {
                name = "ACTION_MOVE";
                break;
            }
            case MotionEvent.ACTION_UP: {
                name = "ACTION_UP";
                break;
            }
            default:
                break;
        }
        return name;
    }

    class MyOnGestureListener extends GestureDetector.SimpleOnGestureListener {
        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            LogUtil.i(getClass().getName(), "onSingleTapUp-----" + getActionName(e.getAction()));
            return false;
        }

        @Override
        public void onLongPress(MotionEvent e) {
            LogUtil.i(getClass().getName(), "onLongPress-----" + getActionName(e.getAction()));
            if (timer!=null){
                timer.cancel();
                timer=null;
            }
            long time = System.currentTimeMillis() - startTime;
            System.out.println("计时结束:" + time);
            final StepLocalBean stepLocalBean = new StepLocalBean();
            stepLocalBean.setTaskTime(time);
            stepLocalBean.setStepType(StepLocalType.LONG_TAP);
            stepLocalBean.setStartPosition(new Point((int) e.getX(), (int) e.getY()));

            FloatViewManager.getInstance().hideCoverView();
            FloatViewManager.getInstance().showMessageView("您执行了“长按”\n坐标（"+(int) e.getX()+","+(int) e.getY()+"）");
            FloatViewManager.getInstance().showCreateMenuView(stepLocalBean);

            new Timer().schedule(new TimerTask() {
                @Override
                public void run() {
                    try {
                        Step.step(StepManager.getService(), stepLocalBean,stepUtil);
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
            }, 500);
        }

        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
            LogUtil.i(getClass().getName(),
                    "onScroll-----" + getActionName(e2.getAction()) + ",(" + e1.getX() + "," + e1.getY() + ") ,("
                            + e2.getX() + "," + e2.getY() + ")");
            return false;
        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            LogUtil.i(getClass().getName(),
                    "onFling-----" + getActionName(e2.getAction()) + ",(" + e1.getX() + "," + e1.getY() + ") ,("
                            + e2.getX() + "," + e2.getY() + ")");

            if (timer!=null){
                timer.cancel();
                timer=null;
            }
            long time = System.currentTimeMillis() - startTime;
            System.out.println("计时结束:" + time);
            final StepLocalBean stepLocalBean = new StepLocalBean();
            stepLocalBean.setTaskTime(time);
            stepLocalBean.setStepType(StepLocalType.SCROLL);
            stepLocalBean.setStartPosition(new Point((int) e1.getX(), (int) e1.getY()));
            stepLocalBean.setEndPosition(new Point((int) e2.getX(), (int) e2.getY()));

            FloatViewManager.getInstance().hideCoverView();
            FloatViewManager.getInstance().showMessageView("您执行了“滑动”" +"\n从(" + (int)e1.getX() + "," + (int)e1.getY() + ") 到(" + (int)e2.getX() + "," + (int)e2.getY() + ")");
            FloatViewManager.getInstance().showCreateMenuView(stepLocalBean);

            new Timer().schedule(new TimerTask() {
                @Override
                public void run() {
                    try {
                        Step.step(StepManager.getService(), stepLocalBean,stepUtil);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }, 500);

            return false;
        }

        @Override
        public void onShowPress(MotionEvent e) {
            LogUtil.i(getClass().getName(), "onShowPress-----" + getActionName(e.getAction()));
        }

        @Override
        public boolean onDown(MotionEvent e) {
            LogUtil.i(getClass().getName(), "onDown-----" + getActionName(e.getAction()));
            return false;
        }

        @Override
        public boolean onDoubleTap(MotionEvent e) {
            LogUtil.i(getClass().getName(), "onDoubleTap-----" + getActionName(e.getAction()));
            return false;
        }

        @Override
        public boolean onDoubleTapEvent(MotionEvent e) {
            LogUtil.i(getClass().getName(), "onDoubleTapEvent-----" + getActionName(e.getAction()));
            return false;
        }

        @Override
        public boolean onSingleTapConfirmed(MotionEvent e) {
            LogUtil.i(getClass().getName(), "onSingleTapConfirmed-----" + getActionName(e.getAction()));

            if (timer!=null){
                timer.cancel();
                timer=null;
            }
            long time = System.currentTimeMillis() - startTime;
            System.out.println("计时结束:" + time);
            final StepLocalBean stepLocalBean = new StepLocalBean();
            stepLocalBean.setTaskTime(time);
            stepLocalBean.setStepType(StepLocalType.SINGLE_TAP);
            stepLocalBean.setStartPosition(new Point((int) e.getX(), (int) e.getY()));

            FloatViewManager.getInstance().hideCoverView();
            FloatViewManager.getInstance().showMessageView("您执行了“单击”\n坐标（"+(int) e.getX()+","+(int) e.getY()+")");
            FloatViewManager.getInstance().showCreateMenuView(stepLocalBean);

            new Timer().schedule(new TimerTask() {
                @Override
                public void run() {
                    try {
                        Step.step(StepManager.getService(), stepLocalBean,stepUtil);
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
            }, 500);
            return false;
        }
    }
}

